package com.bryantkobe.myspringcode.exception;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: 构建器模式 - 支持链式调用创建异常
 * @author: alienwarezzl
 * @date: 2025/9/22
 */
public class Builder {
    private String errorCode;
    private String message;
    private Throwable cause;
    private final Map<String, Object> params = new ConcurrentHashMap<>();

    public Builder errorCode(String errorCode) {
        this.errorCode = errorCode;
        return this;
    }

    public Builder message(String message) {
        this.message = message;
        return this;
    }

    public Builder message(String template, Object... args) {
        this.message = String.format(template, args);
        return this;
    }

    public Builder cause(Throwable cause) {
        this.cause = cause;
        return this;
    }

    public Builder param(String key, Object value) {
        this.params.put(key, value);
        return this;
    }

    public BusinessException build() {
        if (errorCode == null || message == null) {
            throw new IllegalArgumentException("Error code and message are required");
        }
        return new BusinessException(errorCode, message, cause, params);
    }

    /**
     * 静态构建器方法
     */
    public static Builder builder() {
        return new Builder();
    }
}
